package com.demo.accessibility.service

import android.accessibilityservice.AccessibilityService
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.demo.accessibility.Action
import com.blankj.utilcode.util.StringUtils
import com.demo.accessibility.utils.AccessibilityUtils

class NurseHelperService : AccessibilityService() {
    companion object {
        private val TAG: String = NurseHelperService::class.java.name

        @SuppressLint("StaticFieldLeak")
        var instance: NurseHelperService? = null
        fun log(s: String) {
            Log.e(TAG, "============$s")
        }
    }

    private val mAccessibilityEventSubscriberList = mutableListOf<AccessibilityEventSubscriber>()
    fun addAccessibilityEventSubscriber(subscriber: AccessibilityEventSubscriber) {
        if (!mAccessibilityEventSubscriberList.contains(subscriber)) {
            mAccessibilityEventSubscriberList.add(subscriber)
        }
    }

    fun removeAccessibilityEventSubscriber(subscriber: AccessibilityEventSubscriber) {
        if (mAccessibilityEventSubscriberList.contains(subscriber)) {
            mAccessibilityEventSubscriberList.remove(subscriber)
        }
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        log("onAccessibilityEvent$event")
        for (subscriber in mAccessibilityEventSubscriberList) {
            subscriber.onAccessibilityEvent(event)
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        log("onCreate rootInActiveWindow:${rootInActiveWindow}")
        // 开启无障碍服务时，就会立马执行
        AccessibilityUtils.returnApp()
        showNotification()
        registerReceiver(receiver, IntentFilter().apply {
            addAction(Action.CLOSE)
        })
    }

    override fun onInterrupt() {
    }

    fun printRootView() {
        log("开始打印:$rootInActiveWindow")
        log("开始打印:${rootInActiveWindow.window}")
        rootInActiveWindow?.let {
            printAll(it, 0)
            log("==================================")
        }
    }

    fun printAll(nodeInfo: AccessibilityNodeInfo?, level: Int) {
        nodeInfo?.let { nodeInfo ->
            if (nodeInfo.childCount > 0) {
                log("${getBeforeTag(level)}${nodeInfo.className} ${nodeInfo.childCount} 【${nodeInfo.viewIdResourceName}】")
                for (i in 0 until nodeInfo.childCount) {
                    printAll(nodeInfo.getChild(i), level + 1)
                }
            } else {
//                if(nodeInfo.text != null && !nodeInfo.text.equals("")){
//                    log("${getBeforeTag(level)} ${nodeInfo.text}")
//                }
                log("${getBeforeTag(level)}${nodeInfo.className} ${nodeInfo.text} 【${nodeInfo.viewIdResourceName}】")
            }
        }
    }

    fun getAllTextList(minLength: Int = -1): MutableList<String> {
        val list = mutableListOf<String>()
        rootInActiveWindow?.let {
            getAllTextListLoop(it, list, minLength)
        }
        return list
    }

    private fun getAllTextListLoop(
        nodeInfo: AccessibilityNodeInfo?,
        list: MutableList<String>,
        minLength: Int
    ) {
        nodeInfo?.let { nodeInfo ->
            if (nodeInfo.childCount > 0) {
                for (i in 0 until nodeInfo.childCount) {
                    getAllTextListLoop(nodeInfo.getChild(i), list, minLength)
                }
            } else {
                nodeInfo.text?.apply {
                    if (!StringUtils.isSpace("$this")) {
                        if (minLength > 0) {
                            if ("$this".trim().length >= minLength) {
                                list.add("$this".trim())
                            }
                        } else {
                            list.add("$this".trim())
                        }
                    }
                }
            }
        }
    }

    private fun getBeforeTag(level: Int): String {
        val sb = StringBuffer()
        for (i in 0 until level) {
            sb.append("-->")
        }
        return sb.toString()
    }

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, p1: Intent?) {
            when (p1?.action) {
                Action.CLOSE -> {
                    cancelNotification()
                }
            }
        }
    }

    fun showNotification() {
        NotificationHelper.instance.notifyNotification()
        startForeground(
            NotificationHelper.NOTIFICATION_ID,
            NotificationHelper.instance.getNotification()
        )
    }

    fun cancelNotification() {
        stopForeground(true)
    }
}